package org.example.hansp.recursion;

public class EightQueens {
    private static final int SIZE=8;
    private static int[] queens = new int[SIZE];
    private static int solutions = 0;

    public static void main(String[] args) {
        solve(0);
        System.out.println("Total solutions: " + solutions);

    }
    private static void solve(int row){
        if(row==SIZE){
            printSolution();
            solutions++;
            return;
        }
        for(int col=0;col<SIZE;col++){
            if(isSafe(row,col)){
                queens[row]=col;
                solve(row+1);
                // 回溯
                queens[row] = 0;
            }
        }
    }
    private static boolean isSafe(int row, int col) {
        for (int i = 0; i < row; i++) {
            // 检查列冲突和对角线冲突
            if (queens[i] == col || Math.abs(queens[i] - col) == Math.abs(i - row)) {
                return false;
            }
        }
        return true;
    }
    private static void printSolution() {
        for (int i = 0; i < SIZE; i++) {
            for (int j = 0; j < SIZE; j++) {
                if (queens[i] == j) {
                    System.out.print("Q ");
                } else {
                    System.out.print(". ");
                }
            }
            System.out.println();
        }
        System.out.println();
    }
}
